package t4tools.lepath.generate.visitor;

import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;

import t4tools.lepath.annotations.IgnoredFields;
import t4tools.lepath.model.Clazz;
import t4tools.lepath.model.Field;

public class Reader extends ClassVisitor {
	public static final String IGNORED_FIELDS_ANNOTATION_DESCR = Type.getType(IgnoredFields.class).getDescriptor();

	private Clazz clazz;

	public Reader(Class<?> target) {
		super(Opcodes.ASM4);
		this.clazz = new Clazz();
		this.clazz.setTarget(target);
	}

	@Override
	public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
		clazz.setName(name + "_LePath");
	}

	@Override
	public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
		if (IGNORED_FIELDS_ANNOTATION_DESCR.equals(desc)) {
			return new ClassAnnotationReader(getClazz());
		}
		return super.visitAnnotation(desc, visible);
	}

	@Override
	public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
		if (!clazz.getIgnoredFieldNames().contains(name)) {
			Field field = new Field();
			field.setName(name);
			field.setTypeDescr(desc);
			clazz.getFields().add(field);
			return new FieldReader(getClazz(), field);
		}
		return super.visitField(access, name, desc, signature, value);
	}

	public Clazz getClazz() {
		return clazz;
	}

	public void setClazz(Clazz clazz) {
		this.clazz = clazz;
	}
}
